package org.vacoor.xqq.ui.comp.richeditor;

import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.util.ArrayList;

/**
 * User: vacoor
 */
public class Message extends AbstractElement {
    public static final Color DEFAULT_HEADER_COLOR = new Color(0x008040);
    private Text header;
    private Iterable<RichElement> body = new ArrayList<RichElement>();
    private Color headerColor;

    public Message(String header, Iterable<RichElement> body) {
        this(header, body, DEFAULT_HEADER_COLOR);
    }

    public Message(String header, Iterable<RichElement> body, Color headerColor) {
        this.header = new Text(header);
        this.body = body;
        this.headerColor = headerColor;
    }

    @Override
    protected void doInsert(JTextPane textPane, int offset) throws Exception {
        StyledDocument doc = textPane.getStyledDocument();

        SimpleAttributeSet attrSet = new SimpleAttributeSet();
        StyleConstants.setLeftIndent(attrSet, 0F); //不缩进

        header.getStyle().setColor(headerColor);
        header.doInsert(textPane, offset);
        doc.setParagraphAttributes(offset, doc.getLength() - offset, attrSet, false);

        doc.insertString(doc.getLength(), "\r\n", style);

        offset = doc.getLength();
        for (RichElement elem : body) {
            AbstractElement e = (AbstractElement) elem;
            e.doInsert(textPane, doc.getLength());
        }

        StyleConstants.setLeftIndent(attrSet, 15F);
        doc.setParagraphAttributes(offset, doc.getLength() - offset, attrSet, false);
    }
}
